package com.jyw.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.OrderDetail;
import com.jyw.thirdparty.alipay.PayResult;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/6
 */

public class OrderPayActivity extends BaseActivity implements View.OnClickListener {
    private TextView tvGo, tvMoney, tvCoupon;
    private RelativeLayout layoutZFB, layoutWX, layoutXJ, layoutYue, layoutYHQ;
    private RecyclerView recycler;
    private YiAdapter adapter;
    private ImageView tvSelectZFB, tvSelectWX, tvSelectXJ, tvSelectYue;

    private OrderDetail orderDetail;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);
        api.registerApp(WX_APP_ID);

        setContentView(R.layout.activity_order_pay);

        tvGo = (TextView) findViewById(R.id.btn_go);
        tvMoney = (TextView) findViewById(R.id.tv_money);
        tvCoupon = (TextView) findViewById(R.id.tv_coupon);
        layoutZFB = (RelativeLayout) findViewById(R.id.layout_zfb);
        layoutWX = (RelativeLayout) findViewById(R.id.layout_wx);
        layoutXJ = (RelativeLayout) findViewById(R.id.layout_xj);
        layoutYue = (RelativeLayout) findViewById(R.id.layout_yue);
        layoutYHQ = (RelativeLayout) findViewById(R.id.layout_yhq);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        tvSelectZFB = (ImageView) findViewById(R.id.tv_select_zfb);
        tvSelectWX = (ImageView) findViewById(R.id.tv_select_wx);
        tvSelectXJ = (ImageView) findViewById(R.id.tv_select_xj);
        tvSelectYue = (ImageView) findViewById(R.id.tv_select_yue);

        findViewById(R.id.iv_back).setOnClickListener(this);
        tvGo.setOnClickListener(this);
        layoutZFB.setOnClickListener(this);
        layoutWX.setOnClickListener(this);
        layoutXJ.setOnClickListener(this);
        layoutYue.setOnClickListener(this);
        layoutYHQ.setOnClickListener(this);

        recycler.setLayoutManager(new LinearLayoutManager(OrderPayActivity.this));
        recycler.setAdapter(adapter = new YiAdapter());

        loadData();
    }

    class YiAdapter extends RecyclerView.Adapter<YiAdapter.YiHolder> {
        private List<OrderDetail.Yi> data = new ArrayList<>();

        void swapData(List<OrderDetail.Yi> data0) {
            this.data = data0;
            notifyDataSetChanged();
        }

        @Override
        public YiHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new YiHolder(LayoutInflater.from(OrderPayActivity.this).inflate(R.layout.item_yi, null));
        }

        @Override
        public void onBindViewHolder(YiHolder holder, int position) {
            OrderDetail.Yi y = data.get(position);
            holder.tv.setText("衣服编号：" + y.getOrder_id() + "\n衣服名称：" + y.getName() +
                    "          衣服颜色：" + y.getColor() + "\n衣服品牌：" + y.getBrand() +
                    "          衣服数量：" + y.getNumber() + "\n衣服瑕疵：" + y.getFlaw());
        }

        @Override
        public int getItemCount() {
            return data == null ? 0 : data.size();
        }

        class YiHolder extends RecyclerView.ViewHolder {
            TextView tv;

            YiHolder(View itemView) {
                super(itemView);
                tv = (TextView) itemView.findViewById(R.id.tv);
            }
        }
    }

    private void loadData() {
        Request request = new Request.Builder().
                url(Server.GET_ORDER_DETAIL + "?id_data=" + getIntent().getStringExtra("order_id")
                        + "&phone_data=" + getPrefs().getString("phone", "")).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                orderDetail = new Gson().fromJson(response.body().string(), OrderDetail.class);
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        return null;
                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        adapter.swapData(orderDetail.getArr1());
                        String couponMoney = getIntent().getStringExtra("coupon_money");
                        if (!TextUtils.isEmpty(couponMoney)) {
                            int moneyRes = Integer.valueOf(orderDetail.getMoney()) - Integer.valueOf(couponMoney);
                            tvMoney.setText((moneyRes < 0 ? 0 : moneyRes)+"");
                            tvCoupon.setText("(优惠券已抵" + couponMoney + "元)");
                            layoutYHQ.setVisibility(View.VISIBLE);
                            isSelected = R.id.layout_yhq;
                        } else {
                            tvMoney.setText(orderDetail.getMoney());
                            layoutYHQ.setVisibility(View.GONE);
                        }
                    }
                }.execute();
            }
        });
    }

    private int isSelected;

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(OrderPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(OrderPayActivity.this, OrderPaiedActivity.class);
                        intent.putExtra("order_id", orderDetail.getOrder_id());
                        startActivity(intent);
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(OrderPayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(OrderPayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void alipayGo() {
        Request request = new Request.Builder().
                url(Server.GET_PAY_ORDERID + "?money=" + tvMoney.getText().toString()
                        + "&type=alipay").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                aliPay(response.body().string());
            }
        });
    }

    private void aliPay(String orderId) {
        Request request = new Request.Builder().
                url("http://app.jyw0377.com/app/jinyiwei_alipay.php"
                        + "?payid=alipay&type=alipay"
                        + "&order_id=" + orderId
                        + "&appid=dongyijs" + "&total=" + tvMoney.getText().toString()).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String orderInfo = response.body().string();

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        // 构造PayTask 对象
                        PayTask alipay = new PayTask(OrderPayActivity.this);
                        // 调用支付接口，获取支付结果
                        String result = alipay.pay(orderInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        });
    }

    private IWXAPI api;
    private String WX_APP_ID = "wx301cb026f2a8e3ac";

    private void weixinGo() {
        Request request = new Request.Builder().
                url(Server.GET_PAY_ORDERID + "?money=" + tvMoney.getText().toString()
                        + "&type=wxpay").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                weixinPay(response.body().string());
            }
        });
    }

    private void weixinPay(String orderId) {
        final Request request = new Request.Builder().
                url("http://app.jyw0377.com/app/weixin_pay/index.php"
                        + "?payid=wxpay&type=wxpay"
                        + "&order_id=" + orderId
                        + "&appid=dongyijs" + "&total=" + tvMoney.getText().toString()).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    final JSONObject res = new JSONObject(response.body().string());
                    final PayReq payReq = new PayReq();
                    payReq.appId = WX_APP_ID;
                    payReq.partnerId = res.getString("partnerid");
                    payReq.prepayId = res.getString("prepayid");
                    payReq.packageValue = res.getString("package");
                    payReq.nonceStr = res.getString("noncestr");
                    payReq.timeStamp = res.getString("timestamp");
                    payReq.sign = res.getString("sign");
                    payReq.extData = "app data";
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);
                            api.sendReq(payReq);
                        }
                    }.execute();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void yueGo() {
        String coupon_id = getIntent().getStringExtra("coupon_id");
        Request request = new Request.Builder().
                url(Server.ORDER_PAY + "?id=" + orderDetail.getId()
                        + "&type=" + orderDetail.getType()
                        + "&money_data=" + tvMoney.getText().toString()
                        + "&phone_data=" + getPrefs().getString("phone", "")
                        + "&coupon_data=" + (coupon_id.equals("") ? "" : coupon_id) + "&c_id_data=").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body().string().equals("1")) {
                    OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "已支付");
                    Intent intent = new Intent(OrderPayActivity.this, OrderPaiedActivity.class);
                    intent.putExtra("order_id", orderDetail.getOrder_id());
                    startActivity(intent);
                }
            }
        });
    }

    private void cashGo() {
        String coupon_id = getIntent().getStringExtra("coupon_id");
        Request request = new Request.Builder().
                url(Server.ORDER_PAY + "?id=" + orderDetail.getId()
                        + "&type=" + orderDetail.getType()
                        + "&money_data=" + tvMoney.getText().toString()
                        + "&phone_data=" + getPrefs().getString("phone", "")
                        + "&coupon_data=" + (coupon_id.equals("") ? "" : coupon_id) + "&c_id_data=").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body().string().equals("1")) {
                    OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "已支付");
                    Intent intent = new Intent(OrderPayActivity.this, OrderPaiedActivity.class);
                    intent.putExtra("order_id", orderDetail.getOrder_id());
                    startActivity(intent);
                }
            }
        });
    }

    private void yhqGo() {
        String coupon_id = getIntent().getStringExtra("coupon_id");
        Request request = new Request.Builder().
                url(Server.ORDER_PAY + "?id=" + orderDetail.getId()
                        + "&type=" + orderDetail.getType()
                        + "&money_data=" + tvMoney.getText().toString()
                        + "&phone_data=" + getPrefs().getString("phone", "")
                        + "&coupon_data=" + (coupon_id.equals("") ? "" : coupon_id) + "&c_id_data=").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body().string().equals("1")) {
                    OkHttpManager.backgroundThreadShortToast(OrderPayActivity.this, "已支付");
                    Intent intent = new Intent(OrderPayActivity.this, OrderPaiedActivity.class);
                    intent.putExtra("order_id", orderDetail.getOrder_id());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.btn_go:
                switch (isSelected) {
                    case R.id.layout_yhq:
                        yhqGo();
                        break;
                    case R.id.layout_zfb:
                        alipayGo();
                        break;
                    case R.id.layout_wx:
                        weixinGo();
                        break;
                    case R.id.layout_xj:
                        cashGo();
                        break;
                    case R.id.layout_yue:
                        yueGo();
                        break;
                }
                break;
            case R.id.layout_zfb:
                tvSelectZFB.setBackgroundResource(R.drawable.select_succ);
                tvSelectWX.setBackgroundResource(R.drawable.select);
                tvSelectXJ.setBackgroundResource(R.drawable.select);
                tvSelectYue.setBackgroundResource(R.drawable.select);
                isSelected = R.id.layout_zfb;
                break;
            case R.id.layout_wx:
                tvSelectZFB.setBackgroundResource(R.drawable.select);
                tvSelectWX.setBackgroundResource(R.drawable.select_succ);
                tvSelectXJ.setBackgroundResource(R.drawable.select);
                tvSelectYue.setBackgroundResource(R.drawable.select);
                isSelected = R.id.layout_wx;
                break;
            case R.id.layout_xj:
                tvSelectZFB.setBackgroundResource(R.drawable.select);
                tvSelectWX.setBackgroundResource(R.drawable.select);
                tvSelectXJ.setBackgroundResource(R.drawable.select_succ);
                tvSelectYue.setBackgroundResource(R.drawable.select);
                isSelected = R.id.layout_xj;
                break;
            case R.id.layout_yue:
                tvSelectZFB.setBackgroundResource(R.drawable.select);
                tvSelectWX.setBackgroundResource(R.drawable.select);
                tvSelectXJ.setBackgroundResource(R.drawable.select);
                tvSelectYue.setBackgroundResource(R.drawable.select_succ);
                isSelected = R.id.layout_yue;
                break;
        }
    }
}
